from lib.dbobjects import Athlete, Stats, Explanation, RESULTS_DISPLAYED,\
    DAILY_BUDGET
from common import BaseRequestHandler, POSITION_CTRS, THRESHOLD_IMPRESSIONS, \
        populate_athletes, calculate_top_athletes, run_queries

from datetime import datetime

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(BaseRequestHandler):
    def get(self):
        if users.is_current_user_admin():
            self.redirect('/admin')
        else:
            stats = Stats.all().get()
            if stats is None:
                stats = Stats()
                stats.put()
            explanation = Explanation.all().get()
            if explanation is None:
                explanation = Explanation()
                explanation.put()
            athlete = Athlete.all().order('-cpc').get()
            if athlete is None:
                populate_athletes()
            run_queries(stats, 90)
            
            calculate_top_athletes(stats)
            stats.put()
            self.generate('main.html')
            
    def post(self):
        winner_position = int(self.request.get('chosen_athlete'))
        stats_query = Stats.all()
        stats = stats_query.get()
        stats.searches += 1
        for i in xrange(RESULTS_DISPLAYED):
            athlete = Athlete.all().filter("name =", stats.top_names[i]).get()
            if athlete is not None:
                athlete.impressions[i] += 1
                athlete.ec += POSITION_CTRS[i+1]
                # Check if the threshold was reached
                impressions = sum(athlete.impressions)
                if impressions >= THRESHOLD_IMPRESSIONS:
                    athlete.new = False
                athlete.modified = datetime.now()
                if i == winner_position:
                    stats.clicks[i] += 1
                    athlete.clicks[i] += 1
                    athlete.amount_paid += stats.costs[i]
                    if athlete.amount_paid >= DAILY_BUDGET:
                        athlete.out_of_budget = True
                    stats.profit += stats.costs[i]
                athlete.put()
            else:
                raise "Something is wrong, the athlete has to be present"
        if winner_position == RESULTS_DISPLAYED:
            # None was selected
            stats.clicks[i] += 1
        stats.put()
        self.redirect('/')
 
class AdminPage(BaseRequestHandler):
    def get(self):
        if users.is_current_user_admin():
            self.generate("admin.html")
        else:
            self.redirect('/')
            
    def post(self):
        pass


application = webapp.WSGIApplication([('/', MainPage),
                                      ('/admin', AdminPage)], debug=True)


def main():
    run_wsgi_app(application)


if __name__ == "__main__":
    main()
